﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AnalisisDeRiesgos.Models;
using AnalisisDeRiesgos.Models.User;
using Microsoft.Web.Mvc;

namespace AnalisisDeRiesgos.Controllers
{
    public class UserController : Controller
    {
        //
        // GET: /User/

        public ActionResult Index()
        {
            if (!Utils.HasPrivilege(Convert.ToInt32(Session["userid"]), Privileges.Administrator))
                return RedirectToAction("LogOn", "User");

            SearchUserModel model = new SearchUserModel();
            return View(model);
        }

        [HttpPost]
        public ActionResult Index(SearchUserModel model)
        {
            if (ModelState.IsValid)
                model.SearchUsers(model.Pattern);
            return View(model);
        }

        public ActionResult Create()
        {
            if (!Utils.HasPrivilege(Convert.ToInt32(Session["userid"]), Privileges.Administrator))
                return RedirectToAction("LogOn", "User");
            RegisterUserModel model = new RegisterUserModel();
            return View(model);
        }

        [HttpPost]
        public ActionResult Create(RegisterUserModel newUser)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return View(newUser);
                }

                newUser.Save();
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
            }

            
            return View(newUser);
        }

        public ActionResult LogOn()
        {
            if (Convert.ToInt32(Session["userid"]) != 0)
            {
                return RedirectToAction("Index", "Home");
            }
            return View();
        }
        
        [HttpPost]
        public ActionResult LogOn(LogOnModel userInfo)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return View();
                }

                int userId = userInfo.GetUserId();

                Session["userid"] = userId;

                if (userId == 0)
                {
                    ModelState.AddModelError("", "El usuario o la contraseña son incorrectos, intente de nuevo");
                    return View();
                }

                return RedirectToAction("Index", "Home");
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
            }

            return View(userInfo);            
        }

        public ActionResult LogOff()
        {
            Session["userid"] = 0;
            
            return RedirectToAction("LogOn", "User");
        }

        public ActionResult Edit(int? id)
        {
            if (!Utils.HasPrivilege(Convert.ToInt32(Session["userid"]), Privileges.Administrator))
                return RedirectToAction("LogOn", "User");

            if (id == null)
                return RedirectToAction("Index");
            try
            {
                EditUserModel model = new EditUserModel();

                model.FillUserById(id.Value);

                return View(model);
            }
            catch (Exception ex)
            {
                return View("Error", new ErrorModel { Message = ex.Message });
            }
        }

        [HttpPost]
        public ActionResult Edit(EditUserModel model)
        {            
            try
            {
                if (!ModelState.IsValid)
                    return View(model);

                model.Save();
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
            }

            return View(model);
        }

        public ActionResult Details(int? id)
        {
            if (!Utils.HasPrivilege(Convert.ToInt32(Session["userid"]), Privileges.Administrator))
                return RedirectToAction("LogOn", "User");

            if (id == null)
                return RedirectToAction("Index");
            try
            {
                DetailsUserModel model = new DetailsUserModel();

                model.FillUser(id.Value);

                return View(model);
            }
            catch (Exception ex)
            {
                return View("Error", new ErrorModel { Message = ex.Message });
            }
        }

        public ActionResult Delete(int? id)
        {
            if (!Utils.HasPrivilege(Convert.ToInt32(Session["userid"]), Privileges.Administrator))
                return RedirectToAction("LogOn", "User");

            if (id == null)
                return RedirectToAction("Index");
            try
            {
                DetailsUserModel model = new DetailsUserModel();

                model.FillUser(id.Value);

                return View(model);
            }
            catch (Exception ex)
            {
                return View("Error", new ErrorModel { Message = ex.Message });
            }
        }

        [HttpPost]
        public ActionResult Delete(int id)
        {
            DetailsUserModel model = new DetailsUserModel();
            try
            {            
                model.FillUser(id);
                model.DeleteUser(Convert.ToInt32(Session["userid"]));
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
            }

            return View(model);
        }

        public ActionResult Error(ErrorModel errorMsg)
        {
            return View(errorMsg);
        }

        [AcceptAjax]
        public PartialViewResult SearchUser(SearchUserModel model)
        {
            if (model.Pattern == null)
                model.Pattern = "";
            if (ModelState.IsValid)
                model.SearchUsers(model.Pattern);

            return PartialView("SearchUser", model);
        }

        public ActionResult ChangePassword()
        {
            if (!Utils.HasPrivilege(Convert.ToInt32(Session["userid"]), Privileges.Employe))
                return RedirectToAction("LogOn", "User");

            int id = Convert.ToInt32(Session["userid"]);
            try
            {
                ChangePasswordModel model = new ChangePasswordModel();

                model.FillUserById(id);

                return View(model);
            }
            catch (Exception ex)
            {
                return View("Error", new ErrorModel { Message = ex.Message });
            }
        }

        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                    return View(model);

                model.Save();
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
            }

            return View(model);
        }
    }
}
